import type { AxiosInstance, AxiosRequestConfig, AxiosPromise } from 'axios'
import axios from 'axios'
import { showFailToast } from 'vant'
import { tipText } from './config'

const createConfig: AxiosRequestConfig = {}

interface GqlApiData {
  query?: string
  mutation?: string

  [key: string | symbol | number]: any
}
/**
 * graphql查询请求
 */
interface GqlApi {
  (config: AxiosRequestConfig<GqlApiData>): AxiosPromise

  (url: string, config?: AxiosRequestConfig<GqlApiData>): AxiosPromise
}
// @ts-ignore
const api: AxiosInstance & { gql: GqlApi } = axios.create({
  ...createConfig,
})

api.interceptors.request.use(
  (config) => {
    if (!config.baseURL) config.baseURL = !import.meta.env.SSR && import.meta.env.DEV ? '/proxy' : import.meta.env.VITE_BASE_URL
    config.headers['app-version'] = '1.0'
    if (!import.meta.env.SSR) {
      // const userStore = useUserStore()
      // const token = userStore.userInfo?.token
      // if (token) {
      //   config.headers.Authorization = `11 ${token}`
      // }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (!import.meta.env.SSR) {
      const status = error.response.status
      if (status === 403) {
        // 未登录
      } else if (status === 290) {
        showFailToast(tipText.SERVERABNORMAL)
      } else if (status === 429) {
        showFailToast(tipText.SERVERABNORCON)
      } else if (status === 503) {
        showFailToast(tipText.LINKERROR)
      } else {
        showFailToast(tipText.SERVERERROR)
      }
    } else {
      console.error('[api.js error]: ', error)
    }
    return Promise.reject(error)
  }
)

/**
 * graphql查询请求
 */
const gqlApi: GqlApi = (...arg) => {
  const [_url, _config] = arg
  let config: AxiosRequestConfig<GqlApiData> = {}
  if (typeof _url !== 'string') {
    config = { ..._url }
    if (!config.url) config.url = '/index'
  } else {
    if (_config) config = { ...(_config as AxiosRequestConfig<GqlApiData>) }
    config.url = _url
  }
  const _data = config.data || {}
  const type = _data.query === undefined ? 'mutation' : 'query'
  const operationName = _data[type]?.trim().split('(')[0].split(' ')[1]
  config.data = { ..._data, operationName }
  if (!config.baseURL) config.baseURL = !import.meta.env.SSR && import.meta.env.DEV ? '/proxy' : import.meta.env.VITE_BASE_URL
  if (!config.headers) config.headers = {}
  config.method = 'post'
  return api(config)
}
api.gql = gqlApi

export default api
